package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result getListCach() {
        String key=RedisConstants.SHOP_TYPE_KEY;
        // 1.先查缓存
        List<String> strings = stringRedisTemplate.opsForList().range(key, 0, -1);
        if(!strings.isEmpty()){
            // 1.2存在 直接返回 进行流处理 转化为对象
            List<ShopType> collect = strings.stream().map(json -> JSONUtil.toBean(json, ShopType.class)).collect(Collectors.toList());
            return Result.ok(collect);
        }

        // 2.不存在 查数据库
        List<ShopType> sort = this.query().orderByAsc("sort").list();
        if(sort.isEmpty()){
            // 2.1 为空 报错 写缓存空值 null 解决缓存穿透
            stringRedisTemplate.opsForList().rightPush(key,"");
            // 设置有效期兜底
            stringRedisTemplate.expire(key, 30, TimeUnit.SECONDS);
            return Result.fail("店铺类型为空");
        }
        // 3.保存缓存
        // 3.1进行流处理,将集合元素转化为JSON字符串
        List<String> jsonList = sort.stream().map(obj -> {
            return JSONUtil.toJsonStr(obj);
        }).collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(key,jsonList);
        // 3.2设置有效期
        stringRedisTemplate.expire(key,30, TimeUnit.MINUTES);
        // 4.返回数据
        return Result.ok(sort);
    }
}
